import { Injectable } from '@nestjs/common';
import { readFile } from 'fs/promises';
import { ModelAppFactory } from '../../app';
import { Http } from '../../util';

@Injectable()
export class ModelService {

    /**
     * @description 数据请求工具实例对象
     * @type {Http}
     * @memberof ModelService
     */
    http: Http = Http.getInstance();

    /**
     * @description 获取配置
     * @return {*} 
     * @memberof ModelService
     */
    getConfig() {
        const modelApp = ModelAppFactory.getInstance().getActiveApp();
        return {
            type: modelApp.type,
            path: modelApp.path,
            useLocalService: modelApp.useLocalService
        };
    }

    /**
     * 获取所有应用数据
     *
     * @memberof ModelService
     */
    getAllApp() {
        return ModelAppFactory.getInstance().getAllApp();
    }

    /**
     * 设置激活应用
     *
     * @memberof ModelService
     */
    setActiveApp(options: any) {
        ModelAppFactory.getInstance().setActiveApp(options);
        const { codeName, staticResource } = ModelAppFactory.getInstance().getActiveApp();
        return {
            codeName,
            path: staticResource
        }
    }

    /**
     * @description 获取模型
     * @param {string} path 模型路径
     * @return {*} 
     * @memberof ModelService
     */
    async getModel(path: string): Promise<any> {
        if (!path) {
            return {};
        }
        const modelApp = ModelAppFactory.getInstance().getActiveApp();
        let realPath: string = modelApp.getPath(path);
        try {
            const data = await readFile(realPath, 'utf-8');
            return data;
        } catch (error) {
            return {};
        }
    }

    /**
     * @description 更改模型
     * 
     * @memberof ModelService
     */
    public changeModel(options: any) {
        const modelApp = ModelAppFactory.getInstance().getActiveApp();
        const { type, path } = options;
        if (type) {
            modelApp.setType(type);
            modelApp.setPath(path);
        }
        return {
            type: modelApp.type,
            path: modelApp.path
        };
    }
}
